﻿using Tszy.Unlimited.Base.Common;
using Tszy.Unlimited.Base.Infrastructure.Domain;
using Tszy.Unlimited.Base.Infrastructure.Events;

namespace Tszy.Unlimited.Data.UnitOfWorks.Defaults;

/// <summary>
/// 工作单元基类。
/// </summary>
public abstract class DefaultOfWorkBase : IUnitOfWork
{
    [ThreadStatic] private static List<IAggregateRoot> _aggregateRoots = null;

    /// <summary>
    /// 初始化。
    /// </summary>
    protected DefaultOfWorkBase()
    {
        Reset();
        _aggregateRoots = new List<IAggregateRoot>();
    }

    /// <summary>
    /// 增加领域事件。
    /// </summary>
    /// <param name="aggregateRoot">领域实体。</param>
    public static void AddEntity(IAggregateRoot aggregateRoot)
    {
        Check.NotNull(aggregateRoot, nameof(aggregateRoot) + "不可以是空");
        _aggregateRoots?.Add(aggregateRoot);
    }

    /// <summary>
    /// 提交。
    /// </summary>
    public virtual void Commit()
    {
        if (_aggregateRoots != null && _aggregateRoots.Count > 0)
        {
            foreach (var aggregateRoot in _aggregateRoots)
            {
                if (aggregateRoot.DomainEvents.Count > 0)
                {
                    foreach (var domainEvent in aggregateRoot.DomainEvents)
                    {
                        EventManager.Instance.Publish(domainEvent);
                    }
                }
            }
        }

        Reset();
    }

    /// <summary>
    /// 释放资源。
    /// </summary>
    public virtual void Dispose()
    {
        Reset();
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// 重置。
    /// </summary>
    protected virtual void Reset()
    {
        if (_aggregateRoots != null && _aggregateRoots.Count > 0)
        {
            foreach (var aggregateRoot in _aggregateRoots)
            {
                aggregateRoot.ClearEvents();
            }

            _aggregateRoots.Clear();
            _aggregateRoots = null;
        }
    }
}